package com.abc.robot01.fragment

import android.app.Activity
import android.app.DatePickerDialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Gray
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.fragment.app.Fragment
import com.abc.robot01.R
import com.abc.robot01.activity.MYBLACK_Percent40
import com.abc.robot01.activity.MYBLACK_Percent5
import com.abc.robot01.activity.MYWhilte_Percent40
import com.abc.robot01.activity.MyFont_Size
import com.abc.robot01.activity.mysp
import com.abc.robot01.activity.px
import kotlinx.coroutines.launch
import java.util.Calendar


/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class SystemMessageFragment : Fragment() {

    val TAG="系统信息"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val composeView = ComposeView(requireContext()).apply {
            setContent {
                var startDate by remember { mutableStateOf("") }
                var endDate by remember { mutableStateOf("") }

                var refresh = remember { mutableStateOf(true) }

                Box(
                    modifier = Modifier.fillMaxSize()
                ) {
                    Column(modifier = Modifier.offset(x=30.px,y=30.px)) {
                        Row {
                            Button(
                                shape = RoundedCornerShape(10.px),
                                contentPadding=  PaddingValues(0.dp),
                                onClick =  {},
                                colors =  ButtonDefaults.buttonColors(
                                    containerColor = White,
                                    contentColor =  Black
                                ),
                                modifier = Modifier.size(172.px, 60.px)
                            ) {
                                BasicText(
                                    text = "公司信息",
                                    style = TextStyle(
                                        fontWeight= FontWeight.Bold,
                                        fontSize = 28.mysp,
                                    )
                                )
                            }
                            Spacer(modifier = Modifier.width(30.px))

                            Button(
                                shape = RoundedCornerShape(10.px),
                                contentPadding=  PaddingValues(0.dp),
                                onClick =  {},
                                colors =  ButtonDefaults.buttonColors(
                                    containerColor = MYBLACK_Percent5,
                                    contentColor =  Gray
                                ),
                                modifier = Modifier.size(172.px, 60.px)
                            ) {
                                BasicText(
                                    text = "本机信息",
                                    style = TextStyle(
                                        fontWeight= FontWeight.Normal,
                                        fontSize = 28.mysp,
                                    )
                                )
                            }
                        }
                        Spacer(modifier = Modifier.height(30.px))

                        Row {
                            Card(modifier = Modifier
                                .background(MYWhilte_Percent40),
                                shape = RoundedCornerShape(10.px)
                            ) {
                               Row(modifier = Modifier
                                   .size(500.px, 50.px)
                                   .padding(start = 34.px), verticalAlignment = Alignment.CenterVertically) {
                                  Row(modifier = Modifier.width(190.px),verticalAlignment = Alignment.CenterVertically){
                                      BasicText(
                                          text = if(startDate.equals("")) "开始日期"  else  startDate,
                                          style = TextStyle(
                                              color = MYBLACK_Percent40,
                                              fontWeight= FontWeight.Normal,
                                              fontSize = MyFont_Size,
                                          )
                                      )
                                      IconButton(onClick = { showDatePickerDialog(){
                                          startDate=it
                                      } }) {
                                          Icon(
                                              imageVector = Icons.Default.DateRange,
                                              contentDescription = "Select date"
                                          )
                                      }
                                  }

                                   Spacer(modifier = Modifier.width(20.px))
                                   Image(
                                       painter = painterResource(id = R.drawable.toright),
                                       contentDescription = "Image",
                                       contentScale = ContentScale.Crop,
                                   )
                                   Spacer(modifier = Modifier.width(40.px))
                                   BasicText(
                                       text = if(endDate.equals("")) "结束日期" else endDate ,
                                       style = TextStyle(
                                           color = MYBLACK_Percent40,
                                           fontWeight= FontWeight.Normal,
                                           fontSize = MyFont_Size,
                                       )
                                   )
                                   IconButton(onClick = {  showDatePickerDialog(){
                                       endDate=it
                                   } }) {
                                       Icon(
                                           imageVector = Icons.Default.DateRange,
                                           contentDescription = "Select date"
                                       )
                                   }

//                                   Spacer(modifier = Modifier.width(100.px))




//                                   Image(
//                                       modifier = Modifier.clickable {
//                                       },
//                                       painter = painterResource(id = R.drawable.select),
//                                       contentDescription = "Image",
//                                       contentScale = ContentScale.Crop,
//                                   )
                               }
                            }
                        }
                        Spacer(modifier = Modifier.height(10.px))
                        if(refresh.value){
                            MonthList(monthList,refresh)
                            refresh.value =  false
                    }}
                }
            }}
        return composeView
    }

    @Composable
    fun MonthList(monthList: List<MonthData>, refresh: MutableState<Boolean>) {
        Log.e(TAG,"MonthList:"+monthList.size);
        LazyColumn(modifier = Modifier
            .width(1600.px)
            .offset(x = 0.px)) {
            items(monthList) { monthData ->
                MonthSection(monthData,refresh)
            }
        }
    }

    @Composable
    fun MonthSection(monthData: MonthData,refresh: MutableState<Boolean>) {
        Log.e(TAG,"MonthSection:"+monthData.month);
        Log.e(TAG,"MonthSection:"+monthData.items.size);
        Column(modifier = Modifier.padding(0.dp)) {
            Text(
                text = monthData.month,
                style = MaterialTheme.typography.bodyMedium.copy(fontSize = 23.mysp, fontWeight = FontWeight.Normal),
                modifier = Modifier
                    .background(Color.Red)
                    .padding(vertical = 0.dp)
            )
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        color = Color(0x66ffffff),
                        shape = RoundedCornerShape(20.px)
                    )
            )
            {
                Column {
                monthData.items.forEachIndexed() {index, item ->
                    ItemRow(item,refresh)
                    if (index <  monthData.items.size - 1) {
                        HorizontalDivider(
                            modifier = Modifier.padding(horizontal = 16.dp), // Optional padding for the divider
                            thickness = 1.px, // Divider thickness
                            color = Color.Gray // Divider color
                        )
                    }
                }
            }
            }
        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun ItemRow(item: Item,refresh: MutableState<Boolean>) {
        Log.e(TAG,"ItemRow:"+item)
            val scope = rememberCoroutineScope()
            val dismissBoxState = rememberSwipeToDismissBoxState(positionalThreshold={500f})
            SwipeToDismissBox(
                state = dismissBoxState ,
                backgroundContent = {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Transparent),
                        contentAlignment = Alignment.CenterEnd
                    ) {
                      Box(modifier = Modifier.height(100.px).width(120.px).background(Color.Red)) {
                          Text("删除", color = Color.White, fontSize = MyFont_Size, modifier = Modifier.align(Alignment.Center))
                      }
                    }
                },
                content = {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(
                                color = Color(0xFFD6EAF8), // Background color for the item
                                shape = RoundedCornerShape(8.dp) // Rounded corners for the item
                            )
                            .padding(vertical = 8.dp, horizontal = 16.dp)
                            .padding(bottom = 0.dp) // Space between items
                    ) {
                        Row( modifier = Modifier.fillMaxWidth(), // Make Row fill the width of its container
                            verticalAlignment = Alignment.CenterVertically) {
                            Spacer(modifier = Modifier.width(20.px))
                            Image(painter = painterResource(if(item.success) R.drawable.a2 else R.drawable.a4), contentDescription ="" )
                            Spacer(modifier = Modifier.width(30.px))
                            Box(contentAlignment = Alignment.Center, modifier = Modifier.wrapContentSize()) {
                                Image(painter = painterResource(R.drawable.a), contentDescription ="" )
                                Text(text = if(item.success) "渲染成功" else "渲染失败",     style = MaterialTheme.typography.bodyMedium.copy(fontSize = 20.mysp, fontWeight = FontWeight.Normal),color = if(item.success) Color.Blue else Color.Red)
                            }
                            Spacer(modifier = Modifier.width(30.px))
                            Text(text = item.device,     style = MaterialTheme.typography.bodyMedium.copy(fontSize = 23.mysp, fontWeight = FontWeight.Normal), )
                            Spacer(modifier = Modifier.width(30.px))
                            Text(text = item.name,     style = MaterialTheme.typography.bodyMedium.copy(fontSize = 23.mysp, fontWeight = FontWeight.Normal),)
                            Spacer(modifier = Modifier.weight(1f))
                            Text(text = item.date,     style = MaterialTheme.typography.bodyMedium.copy(fontSize = 23.mysp, fontWeight = FontWeight.Normal),)
                        }
                    }

//                    Box(
//                        modifier = Modifier
//                            .fillMaxWidth()
//                            .padding(16.dp)
//                            .background(Color.LightGray)
//                    ) {
//                        Text("Swipe to delete")
//                    }
                }
            )
            LaunchedEffect(dismissBoxState.currentValue) {
                if(dismissBoxState.currentValue == SwipeToDismissBoxValue.EndToStart){
                    scope.launch {
                        delete(item)
                        refresh.value=true
                        Log.e(TAG,"EndToStart");
                    }
                }
            }
    }

//    private fun delete(month:String,name: String){
//        monthList.forEach {
//            if(it.month == month){
//                it.items.removeIf { it.name ==  name }
//                return
//            }
//        }
//    }
//

    private fun showDatePickerDialog(result:(String) -> Unit) {
        val calendar: Calendar = Calendar.getInstance()
        val year: Int = calendar.get(Calendar.YEAR)
        val month: Int = calendar.get(Calendar.MONTH)
        val day: Int = calendar.get(Calendar.DAY_OF_MONTH)

        // Create a DatePickerDialog
        val datePickerDialog = DatePickerDialog(
            requireContext(),
            { view: DatePicker?, selectedYear: Int, selectedMonth: Int, selectedDay: Int ->
                val selectedDate =
                    ""+selectedYear + "/" + (selectedMonth + 1) +"/" +   selectedDay.toString()
                result(selectedDate)
            },
            year, month, day
        )
        datePickerDialog.show()
    }

    override fun onResume() {
        super.onResume()
        Log.e(TAG,"onResume");
    }

    override fun onStart() {
        super.onStart()
        Log.e(TAG,"onStart");
    }

    override fun onPause() {
        super.onPause()
        Log.e(TAG,"onPause");
    }

    override fun onStop() {
        super.onStop()
        Log.e(TAG,"onStop");
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG,"onDestroy");
    }

    override fun onDetach() {
        super.onDetach()
        Log.e(TAG,"onDetach");
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG,"onCreate");
    }

    override fun onAttach(activity: Activity) {
        super.onAttach(activity)
        Log.e(TAG,"onAttach activity");
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        Log.e(TAG,"onAttach Context");
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    companion object {
        val TAG="SystemMessageFragment"
        data class MonthData(val month: String, val items: MutableList<Item>)

        data class Item(
            val success: Boolean = true,
            val device: String = "设备001",
            val name: String = "沿海地中海风格三室两厅",
            val date: String = "2023年7月23日 15:12"
        )

        val monthList = listOf(
            MonthData(
                month = "2023年7月",
                items = mutableListOf(
                    Item(),
                    Item(
                        success = false,
                        device = "设备002",
                        name = "现代简约风格两室一厅",
                        date = "2023年7月24日 10:30"
                    ),
                    Item(
                        device = "设备003",
                        name = "北欧风格四室两厅",
                        date = "2023年7月25日 08:45"
                    ),
                    Item(
                        device = "设备004",
                        name = "新中式风格三室两厅",
                        date = "2023年7月26日 13:20"
                    ),
                    Item(
                        success = true,
                        device = "设备005",
                        name = "田园风格一室一厅",
                        date = "2023年7月27日 16:10"
                    ),
                    Item(
                        success = false,
                        device = "设备006",
                        name = "工业风格开敞空间",
                        date = "2023年7月28日 12:00"
                    ),
                    Item(
                        device = "设备007",
                        name = "美式风格两室两厅",
                        date = "2023年7月29日 14:50"
                    ),
                    Item(
                        success = true,
                        device = "设备008",
                        name = "地中海风格三室两厅",
                        date = "2023年7月30日 11:45"
                    ),
                    Item(
                        success = false,
                        device = "设备009",
                        name = "法式风格一室一厅",
                        date = "2023年7月31日 17:35"
                    ),
                    Item(
                        device = "设备010",
                        name = "英伦风格四室三厅",
                        date = "2023年7月23日 09:00"
                    )
                )
            ),
            MonthData(
                month = "2023年8月",
                items = mutableListOf(
                    Item(
                        success = true,
                        device = "设备011",
                        name = "现代风格单身公寓",
                        date = "2023年8月1日 14:00"
                    ),
                    Item(
                        success = false,
                        device = "设备012",
                        name = "欧式风格两室一厅",
                        date = "2023年8月2日 09:15"
                    ),
                    Item(
                        device = "设备013",
                        name = "美式乡村风格三室两厅",
                        date = "2023年8月3日 15:45"
                    ),
                    Item(
                        success = true,
                        device = "设备014",
                        name = "中式风格两室两厅",
                        date = "2023年8月4日 13:10"
                    ),
                    Item(device = "设备015", name = "工业风格工作室", date = "2023年8月5日 12:30"),
                    Item(
                        success = false,
                        device = "设备016",
                        name = "田园风格别墅",
                        date = "2023年8月6日 08:00"
                    ),
                    Item(
                        device = "设备017",
                        name = "波西米亚风格一室一厅",
                        date = "2023年8月7日 16:20"
                    ),
                    Item(
                        success = true,
                        device = "设备018",
                        name = "北欧风格两室一厅",
                        date = "2023年8月8日 11:05"
                    ),
                    Item(
                        device = "设备019",
                        name = "新古典风格三室两厅",
                        date = "2023年8月9日 10:00"
                    )
                )
            )
        )

        fun delete(item: Item) {
            Log.e(TAG,"delete $item");
            monthList.forEach { month ->
                month.items.removeIf { it.toString() == item.toString() }
            }
        }
    }
}
